package com.zhonghui.mes.controller;

import java.util.List;
import java.util.Objects;
import javax.servlet.http.HttpServletResponse;

import com.zhonghui.common.utils.StringUtils;
import com.zhonghui.mes.domain.MesJobAssemblyItem;
import com.zhonghui.mes.domain.vo.*;
import com.zhonghui.mes.service.IMesPlannedProductionService;
import com.zhonghui.response.BaseResult;
import com.zhonghui.wms.domain.WmsMaterial;
import com.zhonghui.wms.service.IWmsMaterialService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.zhonghui.common.annotation.Log;
import com.zhonghui.common.core.controller.BaseController;
import com.zhonghui.common.core.domain.AjaxResult;
import com.zhonghui.common.enums.BusinessType;
import com.zhonghui.mes.domain.MesJobAssembly;
import com.zhonghui.mes.service.IMesJobAssemblyService;
import com.zhonghui.common.utils.poi.ExcelUtil;
import com.zhonghui.common.core.page.TableDataInfo;

/**
 * 生产作业Controller
 * 
 * @author zhonghui
 * @date 2022-05-21
 */
@Api(tags="制造执行MES-生产作业")
@RestController
@RequestMapping("/mes/jobAssembly")
public class MesJobAssemblyController extends BaseController
{
    @Autowired
    private IMesJobAssemblyService mesJobAssemblyService;

    @Autowired
    private IMesPlannedProductionService mesPlannedProductionService;

    @Autowired
    private IWmsMaterialService materialService;

    /**
     * 查询生产作业列表
     */
    @ApiOperation("查询生产作业列表")
    @GetMapping("/list")
    public TableDataInfo<List<MesInspectionStandardsVo>> list(MesJobAssembly mesJobAssembly)
    {
        startPage();
        List<MesJobAssemblyVo> list = mesJobAssemblyService.selectMesJobAssemblyList(mesJobAssembly);
        return getDataTable(list);
    }

    /**
     * 导出生产作业列表
     */
    @ApiOperation("导出生产作业列表")
    @Log(title = "生产作业", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MesJobAssembly mesJobAssembly)
    {
        List<MesJobAssemblyVo> list = mesJobAssemblyService.selectMesJobAssemblyList(mesJobAssembly);
        ExcelUtil<MesJobAssemblyVo> util = new ExcelUtil<MesJobAssemblyVo>(MesJobAssemblyVo.class);
        util.exportExcel(response, list, "生产作业数据");
    }

    /**
     * 获取生产作业详细信息
     */
    @ApiOperation("获取生产作业详细信息")
    @GetMapping(value = "/{id}")
    public BaseResult<MesJobAssemblyVo> getInfo(@PathVariable("id") Long id)
    {
        return BaseResult.success(mesJobAssemblyService.selectMesJobAssemblyById(id));
    }

    /**
     * 新增生产作业
     */
    @ApiOperation("新增生产作业")
    @Log(title = "生产作业", businessType = BusinessType.INSERT)
    @PostMapping
    public BaseResult<Integer> add(@RequestBody MesJobAssemblyVo mesJobAssemblyVo)
    {
        // 校验排产明细物料是否充足
        MesPlannedProductionVo mesPlannedProductionVo = mesPlannedProductionService.selectMesPlannedProductionById(mesJobAssemblyVo.getPlannedProductionId());
        List<MesPlannedProductionItemVo> mesPlannedProductionItemList = mesPlannedProductionVo.getMesPlannedProductionItemList();
        List<MesJobAssemblyItemVo> mesJobAssemblyItemList = mesJobAssemblyVo.getMesJobAssemblyItemList();
        StringBuilder stringBuilder = new StringBuilder();
        for (MesJobAssemblyItemVo jl : mesJobAssemblyItemList) {
            mesPlannedProductionItemList.stream().filter(pl -> {
                if (Objects.equals(pl.getMaterialId(), jl.getMaterialId())) {
                    double residue = pl.getResidueQuantity() == null ? 0 : pl.getResidueQuantity();
                    if(residue < jl.getUsageQuantity()) {
                        return true;
                    }
                }
                return false;
            }).findAny().ifPresent(pl -> {
                WmsMaterial material = materialService.selectWmsMaterialById(jl.getMaterialId());
                stringBuilder.append("物料[" + material.getMaterialName() + "]剩余数量[" + pl.getResidueQuantity() + "]已不足，不能生产<br/>");
            });
        }
        String msg = stringBuilder.toString();
        if (StringUtils.isNotBlank(msg)) {
            return BaseResult.error(msg);
        }
        return BaseResult.success(mesJobAssemblyService.insertMesJobAssembly(mesJobAssemblyVo));
    }

    /**
     * 修改生产作业
     */
    @ApiOperation("修改生产作业")
    @Log(title = "生产作业", businessType = BusinessType.UPDATE)
    @PutMapping
    public BaseResult<Integer> edit(@RequestBody MesJobAssemblyVo mesJobAssemblyVo)
    {
        return BaseResult.success(mesJobAssemblyService.updateMesJobAssembly(mesJobAssemblyVo));
    }

    /**
     * 修改生产作业状态
     */
    @ApiOperation("修改生产作业状态")
    @Log(title = "生产作业", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public BaseResult<Integer> changeStatus(@RequestBody MesJobAssemblyVo mesJobAssemblyVo)
    {
        Integer status = mesJobAssemblyVo.getStatus();
        //执行生产校验物料是否充足
        if (status == 1) {
            MesJobAssemblyVo job = mesJobAssemblyService.selectMesJobAssemblyById(mesJobAssemblyVo.getId());
            MesPlannedProductionVo mesPlannedProductionVo = mesPlannedProductionService.selectMesPlannedProductionById(job.getPlannedProductionId());
            List<MesPlannedProductionItemVo> mesPlannedProductionItemList = mesPlannedProductionVo.getMesPlannedProductionItemList();
            List<MesJobAssemblyItemVo> mesJobAssemblyItemList = job.getMesJobAssemblyItemList();
            StringBuilder stringBuilder = new StringBuilder();
            for (MesJobAssemblyItemVo jl : mesJobAssemblyItemList) {
                mesPlannedProductionItemList.stream().filter(pl -> {
                    if (Objects.equals(pl.getMaterialId(), jl.getMaterialId())) {
                        double residue = pl.getResidueQuantity() == null ? 0 : pl.getResidueQuantity();
                        if(residue < jl.getUsageQuantity()) {
                            return true;
                        }
                    }
                    return false;
                }).findAny().ifPresent(pl -> {
                    WmsMaterial material = materialService.selectWmsMaterialById(jl.getMaterialId());
                    stringBuilder.append("物料[" + material.getMaterialName() + "]剩余数量[" + pl.getResidueQuantity() + "]已不足，不能生产<br/>");
                });
            }
            String msg = stringBuilder.toString();
            if (StringUtils.isNotBlank(msg)) {
                return BaseResult.error(msg);
            }
        }
        return BaseResult.success(mesJobAssemblyService.updateMesJobAssemblyStatus(mesJobAssemblyVo));
    }

    /**
     * 删除生产作业
     */
    @ApiOperation("删除生产作业")
    @Log(title = "生产作业", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public BaseResult<Integer> remove(@PathVariable Long[] ids)
    {
        return BaseResult.success(mesJobAssemblyService.deleteMesJobAssemblyByIds(ids));
    }
}
